package com.grantha.controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.grantha.util.DB;
import com.grantha.util.Util;

/**
 * Servlet implementation class PatronSearchServlet
 */
@WebServlet("/PatronSearchServlet")
public class PatronSearchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		
		String QueryName = request.getParameter("QueryName");
		String SearchType = request.getParameter("SearchType");
		String SearchColumn = request.getParameter("SearchColumn");
		int length = QueryName.length();
		
		if(QueryName == ""){
			out.print(Util.sendJSONMessage(false, "the feild is required"));
			}
			
			else if(length < 3){
				out.print(Util.sendJSONMessage(false, "Need atleast three characters"));
			}
		
		int SearchTypeInt = Integer.parseInt(SearchType);
		String SearchQueryLastPart = "";
		
		switch (SearchTypeInt) {
		case 0:
			SearchQueryLastPart = " like ? ";
			QueryName = QueryName+"%";
			break;
		case 1:
			SearchQueryLastPart = " = ? ";
			break;
		case 2:
			SearchQueryLastPart = " like ? ";
			QueryName = "%"+QueryName;
			break;
		case 3:
			SearchQueryLastPart = " like ? ";
			QueryName = "%"+QueryName+"%";
			break;
		}
		
		try {
			ResultSet rs =  DB.search("select PatNo, Name, GuranterName, Phone from PatronRegister where "+SearchColumn+SearchQueryLastPart, QueryName);
			
			JSONArray jArr = new JSONArray();
			JSONObject jObj ;
			while(rs.next()){
				jObj = new JSONObject();
				jObj.put("PatNo", rs.getString("PatNo"));
				jObj.put("Name", rs.getString("Name"));
				jObj.put("GuranterName", rs.getString("GuranterName"));
				jObj.put("Phone", rs.getString("Phone"));
				
				jArr.add(jObj);
				
			}
			
			out.write(jArr.toString());
			out.close();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
